import $ from '@/common'
import Vue from 'vue'
export default {
  state: {
    treeData: [{
      expand: true,
      title: 'parent 1',
      children: [{
        title: 'parent 1-0',
        expand: true,
        disabled: true,
        children: [{
          title: 'leaf',
          disableCheckbox: true
        }, {
          title: 'leaf'
        }]
      }, {
        title: 'parent 1-1',
        expand: true,
        checked: true,
        children: [{
          title: 'leaf'
        }]
      }]
    }]
  },
  actions: {
    // 查询主树的数据 
    fetchMain() {},
    // 展开查询数据 
    fetchChild() {}
  },
  mutations: {
    openAll(state) {
      $.eachChild({
        data: state.treeData,
        handler(data) {
          data.expand = true
        }
      })
    },
    closeAll(state) {
      $.eachChild({
        data: state.treeData,
        handler(data) {
          data.expand = false
        }
      })
    },
    checkAll(state, v) {
      $.eachChild({
        data: state.treeData,
        handler(data) {
          data.checked = v
        }
      })
    },
    setData(state, data) {
      Vue.set(state, 'treeData', data)
    },
    setTreeData(state, data) {
      var treeData = []
      $.eachChild({
        data,
        handler(item, deep) {
          if (deep === 0) {
            item.show = true
            item.checked = false
            treeData.push(item)
          }
          item.expand = true
        }
      })
      Vue.set(state, 'treeData', treeData)
    },
    treeLocalFilter(state, key) {
      // 待优化，当父元素隐藏，子元素显示时，祖先元素也要显示
      $.eachChild({
        data: state.treeData,
        handler(data) {
          if (data.name && data.name.indexOf(key) >= 0) {
            data.show = true
          } else {
            data.show = false
          }
        },
        // 递归处理，从子节点开始，若子节点显示，则父节点也要显示
        after(data, deep, parent) {
          if (parent && data.show) {
            parent.show = true
          }
        }
      })
    }
  }
}
